<template>
  <div class="updateName">
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('colose-name')"
      @click-right="onSubmit"
    />
    <van-cell-group>
      <van-field
        v-model.trim="localName"
        placeholder="请输入昵称"
        autosize
        autofocus
        maxlength="8"
        show-word-limit
      />
    </van-cell-group>
  </div>
</template>
<script>
import { setUserInfo } from '@/api/user'
import { Toast } from 'vant'
export default {
  name: 'UpdateName',
  data () {
    return {
      localName: this.value
    }
  },
  created () {},
  methods: {
    async onSubmit () {
      Toast.loading({
        message: '保存中...',
        forbidClick: true
      })
      if (!this.localName) {
        Toast.fail('无效昵称')
        return
      }
      if (this.localName === this.value) {
        Toast.fail('昵称未修改')
        return
      }
      try {
        await setUserInfo({
          nickname: this.localName
        })
        this.$emit('colose-name')
        Toast.success('保存成功')
        this.$emit('input', this.localName)
      } catch (error) {
        if (error && error.response && error.response.status === 409) {
          Toast.fail('昵称已存在,修改失败')
        }
        return error
      }
    }
  },
  components: {},
  props: {
    value: {
      type: String,
      required: true
    }
  },
  watch: {},
  computed: {},
  mounted () {}
}
</script>

<style lang="less" scoped></style>
